package thread;

/**
 * 互斥性
 * 当使用多个synchronized锁定多个代码片段,并且指定的同步监视器对象相同时,这些代码片段就是互斥的.
 * 多个线程不能同时执行这些代码片段.
 *
 */
public class SyncDemo4 {
    public static void main(String[] args) {
        Foo foo = new Foo();
        Thread t1 = new Thread("老六"){
            public void run(){
                foo.methodA();
            }
        };
        Thread t2 = new Thread("小方"){
            public void run(){
                foo.methodB();
            }
        };
        t1.start();
        t2.start();
    }
}

class Foo {
    public synchronized void methodA(){
        try {
            Thread t = Thread.currentThread();
            System.out.println(t.getName()+":正在踢足球...");
            Thread.sleep(5000);
            System.out.println(t.getName()+":啪！");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    public synchronized void methodB(){
        try {
            Thread t = Thread.currentThread();
            System.out.println(t.getName()+":正在玩泥巴...");
            Thread.sleep(5000);
            System.out.println(t.getName()+":啪！谁啊...");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

